#include "cpurankmvccomparemainwindow.h"
#include "ui_cpurankmvccomparemainwindow.h"

#include <QtWebEngineWidgets>
#include <httpclient.h>
#include <qrcutil.h>

#include <src/ui/widgets/cpurankitem.h>
#include <src/ui/widgets/cpurankitemdelegate.h>
#include <src/ui/widgets/cpurankviewmodel.h>

CpuRankMVCCompareMainWindow::CpuRankMVCCompareMainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::CpuRankMVCCompareMainWindow)
{
    ui->setupUi(this);

    ui->webView->load(QUrl("https://cpu.bmcx.com/6382_5493__cpu/"));

    connect(ui->webView, &QWebEngineView::loadFinished, this, [=](bool finished){
        static bool zoom_changed = false;

        if (finished)
            ui->webView->page()->runJavaScript(QR("://javascript.js"));

        qreal currentZoom = ui->webView->page()->zoomFactor();
        setWindowTitle(QString("currentZoom = %1  > 1.5").arg(currentZoom));

        if (!zoom_changed) {
            zoom_changed = true;

            if (currentZoom == 1) {
                ui->webView->setZoomFactor(1.5);
            }
        }
    });

    // ----------------

    CpuRankViewModel *cpu_rank_model = new CpuRankViewModel;
    CpuRankItemDelegate *cpu_rank_delegate = new CpuRankItemDelegate;
    ui->cpu_rank_list->setModel(cpu_rank_model);
    ui->cpu_rank_list->setItemDelegate(cpu_rank_delegate);

    Response resp = HttpClient::instance().get("https://cpu.bmcx.com/web_system/bmcx_com_www/system/file/cpu/get_data/?lx=cpu&s=1&e=999999");
    if (resp.ok()) {
        for (const auto &var : resp.toList()) {
            cpu_rank_model->append(new CpuRankInfo(var.toMap()));
        }
    }

    // [2] 实现模型数据过滤
    QSortFilterProxyModel *cpu_rank_proxy_model = new QSortFilterProxyModel(this);
    cpu_rank_proxy_model->setSourceModel(cpu_rank_model); // 绑定源模型
    cpu_rank_proxy_model->setFilterRole(CpuRankViewModel::CpuRankMingCheng); // 指定过滤角色
    ui->cpu_rank_list->setModel(cpu_rank_proxy_model);

    connect(ui->cpu_filter, &QLineEdit::textChanged, [=](const QString &text){
        // 同步过滤条件到代理模型
        if (text.isEmpty()) {
            cpu_rank_proxy_model->setFilterFixedString(text); // 清空过滤
        } else {
            cpu_rank_proxy_model->setFilterWildcard(text); // 设置通配符过滤（支持模糊匹配）
        }
    });

    // -----------------

    connect(cpu_rank_delegate, &CpuRankItemDelegate::switchIdChagned, this, [=](const QString &id, bool switched){
        if (switched) {
            m_cpuids.append(id);
        } else {
            m_cpuids.removeAll(id);
        }
        if (not m_cpuids.isEmpty())
            ui->webView->load(QUrl(QString("https://cpu.bmcx.com/%1__cpu/").arg(m_cpuids.join("_"))));
    });

    ui->cpu_rank_list->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection);

    // --------------
    ui->splitter->setSizes(QList<int>() << width() / 2 << width() / 2);
}

CpuRankMVCCompareMainWindow::~CpuRankMVCCompareMainWindow()
{
    delete ui;
}
